// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pybind11/stl.h>
#include <pollux/common/memory/memory.h>
#include <pollux/core/query_ctx.h>

namespace kumo::pollux::py {

/// PyPolluxContext is used only during function binding time. Its a utility
/// that manages pool, query and exec context for Pollux expressions and vectors.
struct PyPolluxContext {
  static inline PyPolluxContext& getSingletonInstance() {
    if (!instance_) {
      instance_ = std::unique_ptr<PyPolluxContext>(new PyPolluxContext());
    }
    return *instance_.get();
  }

  kumo::pollux::memory::MemoryPool* pool() {
    return pool_.get();
  }

  kumo::pollux::core::QueryCtx* queryCtx() {
    return queryCtx_.get();
  }

  kumo::pollux::core::ExecCtx* execCtx() {
    return execCtx_.get();
  }

  static inline void cleanup() {
    if (instance_) {
      instance_.reset();
    }
  }

 private:
  PyPolluxContext() = default;
  PyPolluxContext(const PyPolluxContext&) = delete;
  PyPolluxContext(const PyPolluxContext&&) = delete;
  PyPolluxContext& operator=(const PyPolluxContext&) = delete;
  PyPolluxContext& operator=(const PyPolluxContext&&) = delete;

  std::shared_ptr<kumo::pollux::memory::MemoryPool> pool_ =
      kumo::pollux::memory::deprecatedAddDefaultLeafMemoryPool();
  std::shared_ptr<kumo::pollux::core::QueryCtx> queryCtx_ =
      kumo::pollux::core::QueryCtx::create();
  std::unique_ptr<kumo::pollux::core::ExecCtx> execCtx_ =
      std::make_unique<kumo::pollux::core::ExecCtx>(
          pool_.get(),
          queryCtx_.get());

  static inline std::unique_ptr<PyPolluxContext> instance_;
};

} // namespace kumo::pollux::py
